package com.hwpt.hwaccount.feature.auth;

import android.widget.Button;

import com.hwpt.hwaccount.feature.auth.utils.AuthValidator;

import java.lang.ref.WeakReference;

public class AuthPresenter implements AuthContract.Presenter {
    private WeakReference<AuthContract.View> viewRef;
    private final AuthContract.Model model;
    private String registerPhone; //保存注册手机号
    private boolean isLoginTabSelected = true;
    private boolean isVerifyCodeLogin = true;
    public boolean isRegisterFirstStep = true;

    public AuthPresenter(AuthContract.Model model) {
        this.model = model;
    }

    @Override
    public void attachView(AuthContract.View view) {
        this.viewRef = new WeakReference<>(view);
    }

    @Override
    public void detachView() {
        if (viewRef != null) {
            viewRef.clear();
        }
    }

    @Override
    public void onDestroy() {
        detachView();
    }

    @Override
    public void onTabSelected(boolean isLogin) {
        isLoginTabSelected = isLogin;
        AuthContract.View view = viewRef.get();
        if (view != null) {
            view.switchTab(isLogin);
            view.updateTabUI();
        }
    }

    @Override
    public void onSwitchLoginType() {
        isVerifyCodeLogin = !isVerifyCodeLogin;
        AuthContract.View view = viewRef.get();
        if (view != null) {
            view.updateLoginTypeUI();
        }
    }

    @Override
    public void onForgetPassword() {
        AuthContract.View view = viewRef.get();
        if (view != null) {
            view.navigateToRepwdActivity();
        }
    }

    //TODO隐私政策待实现
    @Override
    public void onPrivacyClicked() {
        AuthContract.View view = viewRef.get();
        if (view != null) {
            view.showError("隐私政策详情待展示");
        }
    }

    @Override
    public void onSkipClicked() {
        AuthContract.View view = viewRef.get();
        if (view != null) {
            view.finishActivity();
        }
    }

    @Override
    public void onGetVerifyCode(Button button) {
        AuthContract.View view = viewRef.get();
        if (view == null) return;

        String phone;
        if (button == view.getRegisterVerifyCodeButton()) {
            // 注册页面的验证码获取
            phone = view.getRegisterPhone();
            String phoneError = AuthValidator.getPhoneError(phone);
            if (phoneError != null) {
                view.showPhoneError(phoneError);
                return;
            }

            // 先发送验证码请求，成功后再开始倒计时
            model.RegisterSendCode(phone, new AuthContract.Model.VerifyCodeCallback() {
                @Override
                public void onSuccess() {
                    AuthContract.View v = viewRef.get();
                    if (v != null) {
                        v.startCountDown(button, 60000); // 发送成功后再开始倒计时
                        v.showSuccess("验证码已发送");
                    }
                }

                @Override
                public void onFailure(String error) {
                    AuthContract.View v = viewRef.get();
                    if (v != null) {
                        v.showError(error);
                        // 不需要重置按钮，因为倒计时还没开始
                    }
                }
            });

        } else {
            // 登录页面的验证码获取
            String account = view.getLoginAccount();
            String accountError = AuthValidator.getAccountError(account);
            if (accountError != null) {
                view.showAccountError(accountError);
                return;
            }
            phone = account; // 登录时账号就是手机号

            // 先发送验证码请求，成功后再开始倒计时
            model.LoginSendCode(phone, new AuthContract.Model.VerifyCodeCallback() {
                @Override
                public void onSuccess() {
                    AuthContract.View v = viewRef.get();
                    if (v != null) {
                        v.startCountDown(button, 60000); // 发送成功后再开始倒计时
                        v.showSuccess("验证码已发送");
                    }
                }

                @Override
                public void onFailure(String error) {
                    AuthContract.View v = viewRef.get();
                    if (v != null) {
                        v.showError(error);
                        // 不需要重置按钮，因为倒计时还没开始
                    }
                }
            });
        }
    }
    @Override
    public void onLogin() {
        AuthContract.View view = viewRef.get();
        if (view == null) return;

        String account = view.getLoginAccount();
        String accountError = AuthValidator.getAccountError(account);
        if (accountError != null) {
            view.showAccountError(accountError);
            return;
        }

        if (isVerifyCodeLogin) {
            String verifyCode = view.getVerifyCode();
            String verifyCodeError = AuthValidator.getVerifyCodeError(verifyCode);
            if (verifyCodeError != null) {
                view.showError(verifyCodeError);
                return;
            }

            model.loginWithVerifyCode(account, verifyCode, new AuthContract.Model.VerifyCodeCallback() {
                @Override
                public void onSuccess() {
                    AuthContract.View v = viewRef.get();
                    if (v != null) {
                        v.showSuccess("登录成功");
                        v.navigateToHomeActivity();
                    }
                }

                @Override
                public void onFailure(String error) {
                    AuthContract.View v = viewRef.get();
                    if (v != null) {
                        v.showError(error);
                    }
                }
            });
        } else {
            String password = view.getPassword();
            String passwordError = AuthValidator.getPasswordError(password);
            if (passwordError != null) {
                view.showError(passwordError);
                return;
            }

            model.loginWithPwd(account, password, new AuthContract.Model.LoginCallback() {
                @Override
                public void onSuccess(String response) {
                    AuthContract.View v = viewRef.get();
                    if (v != null) {
                        v.showSuccess("登录成功");
                        v.navigateToHomeActivity();
                    }
                }

                @Override
                public void onFailure(String error) {
                    AuthContract.View v = viewRef.get();
                    if (v != null) {
                        v.showError(error);
                    }
                }
            });
        }
    }

    //验证码校验
    @Override
    public void RegisterVerifyCode() {
        AuthContract.View view = viewRef.get();
        if (view == null) return;

        String phone = view.getRegisterPhone();
        String verifyCode = view.getRegisterVerifyCode();

        String phoneError = AuthValidator.getPhoneError(phone);
        if (phoneError != null) {
            view.showError(phoneError);
            return;
        }

        String verifyCodeError = AuthValidator.getVerifyCodeError(verifyCode);
        if (verifyCodeError != null) {
            view.showError(verifyCodeError);
            return;
        }


        model.RegisterVerifyCode(phone, verifyCode, new AuthContract.Model.VerifyCodeCallback() {
            @Override
            public void onSuccess() {
                // 只有在服务器验证成功后才更新状态
                registerPhone = phone;
                isRegisterFirstStep = false;

                AuthContract.View view = viewRef.get();
                if (view != null) {
                    view.updateRegisterFormUI();
                    view.displayRegisterPhone(phone);
                    view.showSuccess("验证码验证成功");
                }
            }

            @Override
            public void onFailure(String errorMsg) {
                AuthContract.View view = viewRef.get();
                if (view != null) {
                    view.showError(errorMsg);
                    // 保持第一步状态，不跳转
                    isRegisterFirstStep = true;
                }
            }
        });
    }

    @Override
    public void onRegister() {
        AuthContract.View view = viewRef.get();
        if (view == null) return;

        // 使用保存的手机号，而不是重新获取
        String phone = this.registerPhone;
        String password = view.getSetPassword();
        String confirmPassword = view.getConfirmPassword();

        String passwordError = AuthValidator.getPasswordError(password);
        if (passwordError != null) {
            view.showError(passwordError);
            return;
        }

        if (!password.equals(confirmPassword)) {
            view.showError("两次输入的密码不一致");
            return;
        }

        model.register(phone, password, confirmPassword, new AuthContract.Model.RegisterCallback() {
            @Override
            public void onSuccess(String response) {
                AuthContract.View v = viewRef.get();
                if (v != null) {
                    v.showSuccess("注册成功");
                    // 重置注册状态
                    resetRegisterState();
                    // 切换到登录标签页
                    isLoginTabSelected = true;
                    v.switchTab(true);
                    v.updateTabUI();
                    // 自动填充登录账号
                    v.setLoginAccount(phone);
                }
            }

            @Override
            public void onFailure(String error) {
                AuthContract.View v = viewRef.get();
                if (v != null) {
                    v.showError(error);
                }
            }
        });
    }

    @Override
    public void resetRegisterState() {
        isRegisterFirstStep = true;
        registerPhone = null;
    }

    @Override
    public boolean isLoginTabSelected() {
        return isLoginTabSelected;
    }

    @Override
    public boolean isVerifyCodeLogin() {
        return isVerifyCodeLogin;
    }

    @Override
    public boolean isRegisterFirstStep() {
        return isRegisterFirstStep;
    }
}